package pl.ciaastek.ubuntucontrol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;

class MakeConnection extends AsyncTask<String, String, String> {

	private Context context;
	ProgressDialog dialog;
	String com;
	Connection connection;

	public MakeConnection(Context cxt, Connection conn) {

		connection = conn;
		context = cxt;
		dialog = new ProgressDialog(context);
	}

	@Override
	protected void onPreExecute() {
		dialog.setMessage("");
		dialog.setCancelable(false);
		dialog.show();
	}

	protected void onProgressUpdate(String... progress) {
		String tmpStr = (String) progress[0];
		dialog.setMessage(tmpStr);
	}

	protected void onPostExecute(String result) {
		if (dialog.isShowing()) {
			dialog.dismiss();
		}
		context.startActivity(connection.intent);
		return;
	}

	@Override
	protected String doInBackground(String... some) {
		String result = "";
		Properties props = new Properties();
		props.put("StrictHostKeyChecking", "no");
		
		publishProgress("Inicjalizacja");
		result += "1\n";

		String host = some[0];
		int port = Integer.parseInt(some[1]);
		String user = some[2];
		String pwd = some[3];
		
		publishProgress("Konfiguracja");
		result += "2\n";

		Properties config = new Properties();
		config.put("StrictHostKeyChecking", "no");
		config.put("compression.s2c", "zlib,none");
		config.put("compression.c2s", "zlib,none");

		JSch jsch = new JSch();
		
		publishProgress("Łączę z serwerem");
		result += "3\n";

		try {
			connection.session = jsch.getSession(user, host, port);
			SettingsActivity.session = connection.session;
		} catch (JSchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		connection.session.setConfig(config);
		connection.session.setPassword(pwd);
		try {
			connection.session.connect();
		} catch (JSchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		publishProgress("Podłączanie do shell");
		result += "3\n";

		try {
			connection.channel = connection.session.openChannel("shell");
			connection.fromServer = new BufferedReader(new InputStreamReader(
					connection.channel.getInputStream()));
			connection.toServer = connection.channel.getOutputStream();
			connection.channel.connect();

		} catch (JSchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		publishProgress("Podłączono pod shell");
		result += "n\n";
		result += "All steps executed!";
		return result;
	}

}
